package com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.repository.HddcGeochemicalabnpointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.repository.HddcGeochemicalabnpointRepository;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.repository.entity.HddcGeochemicalabnpointEntity;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.service.HddcGeochemicalabnpointService;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.viewobjects.HddcGeochemicalabnpointPageVO;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.viewobjects.HddcGeochemicalabnpointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeochemicalAbnPoint.viewobjects.HddcGeochemicalabnpointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地球化学探测异常点-点
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcGeochemicalabnpointServiceImpl implements HddcGeochemicalabnpointService {

    private final HddcGeochemicalabnpointRepository hddcGeochemicalabnpointRepository;
    private final HddcGeochemicalabnpointNativeRepository hddcGeochemicalabnpointNativeRepository;
    private final GeochemicalExploreExceptionPointExcelVerifyHandler geochemicalExploreExceptionPointExcelVerifyHandler;

    @Autowired
    public HddcGeochemicalabnpointServiceImpl(HddcGeochemicalabnpointRepository hddcGeochemicalabnpointRepository,
                                              HddcGeochemicalabnpointNativeRepository hddcGeochemicalabnpointNativeRepository,
                                              GeochemicalExploreExceptionPointExcelVerifyHandler geochemicalExploreExceptionPointExcelVerifyHandler) {
        this.hddcGeochemicalabnpointRepository = hddcGeochemicalabnpointRepository;
        this.hddcGeochemicalabnpointNativeRepository = hddcGeochemicalabnpointNativeRepository;
        this.geochemicalExploreExceptionPointExcelVerifyHandler = geochemicalExploreExceptionPointExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcGeochemicalabnpoints(HddcGeochemicalabnpointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeochemicalabnpointPageVO> hddcGeochemicalabnpointPage = this.hddcGeochemicalabnpointNativeRepository.queryHddcGeochemicalabnpoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcGeochemicalabnpointPage);
    }

    @Override
    public HddcGeochemicalabnpointEntity getHddcGeochemicalabnpoint(String id) {
        return this.hddcGeochemicalabnpointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeochemicalabnpointEntity saveHddcGeochemicalabnpoint(HddcGeochemicalabnpointEntity hddcGeochemicalabnpoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeochemicalabnpoint.setUuid(uuid);
        hddcGeochemicalabnpoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcGeochemicalabnpoint.setCreateTime(now);
        hddcGeochemicalabnpoint.setUpdateTime(now);
        hddcGeochemicalabnpoint.setIsValid(PlatformConstants.Y);
        hddcGeochemicalabnpoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcGeochemicalabnpoint.setExtends10(PlatformConstants.Y);
        this.hddcGeochemicalabnpointRepository.save(hddcGeochemicalabnpoint);
        return hddcGeochemicalabnpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeochemicalabnpointEntity updateHddcGeochemicalabnpoint(HddcGeochemicalabnpointEntity hddcGeochemicalabnpoint) {
        HddcGeochemicalabnpointEntity entity = hddcGeochemicalabnpointRepository.findById(hddcGeochemicalabnpoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeochemicalabnpoint);
        hddcGeochemicalabnpoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeochemicalabnpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeochemicalabnpointRepository.save(hddcGeochemicalabnpoint);
        return hddcGeochemicalabnpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeochemicalabnpoints(List<String> ids) {
        List<HddcGeochemicalabnpointEntity> hddcGeochemicalabnpointList = this.hddcGeochemicalabnpointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeochemicalabnpointList) && hddcGeochemicalabnpointList.size() > 0) {
            for(HddcGeochemicalabnpointEntity hddcGeochemicalabnpoint : hddcGeochemicalabnpointList) {
                hddcGeochemicalabnpoint.setIsValid(PlatformConstants.N);
                hddcGeochemicalabnpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeochemicalabnpoint.setUpdateTime(new Date());
                this.hddcGeochemicalabnpointRepository.save(hddcGeochemicalabnpoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcGeochemicalabnpointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeochemicalabnpointEntity> yhDisasterEntities = hddcGeochemicalabnpointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeochemicalabnpointVO> list=new ArrayList<>();
        for (HddcGeochemicalabnpointEntity entity:yhDisasterEntities) {
            HddcGeochemicalabnpointVO yhDisasterVO=new HddcGeochemicalabnpointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地球化学探测异常点-点","地球化学探测异常点-点",
                HddcGeochemicalabnpointVO.class,"地球化学探测异常点-点.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(geochemicalExploreExceptionPointExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcGeochemicalabnpointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeochemicalabnpointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcGeochemicalabnpointVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcGeochemicalabnpointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcGeochemicalabnpointVO> list) {
        for (HddcGeochemicalabnpointVO hddcGeochemicalabnpointVO : list) {
            HddcGeochemicalabnpointEntity yhDisasterEntity = new HddcGeochemicalabnpointEntity();
            BeanUtils.copyProperties(hddcGeochemicalabnpointVO, yhDisasterEntity);
            saveHddcGeochemicalabnpoint(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeochemicalabnpointEntity> hddcGeochemicalabnpointList = this.hddcGeochemicalabnpointRepository.queryHddcGeochemicalabnpointsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeochemicalabnpointList) && hddcGeochemicalabnpointList.size() > 0) {
            for(HddcGeochemicalabnpointEntity hddcGeochemicalabnpoint : hddcGeochemicalabnpointList) {
                hddcGeochemicalabnpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeochemicalabnpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeochemicalabnpoint.setIsValid(PlatformConstants.N);
                this.hddcGeochemicalabnpointRepository.save(hddcGeochemicalabnpoint);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeochemicalabnpointEntity> hddcGeochemicalabnpointList = this.hddcGeochemicalabnpointRepository.queryHddcGeochemicalabnpointsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeochemicalabnpointList) && hddcGeochemicalabnpointList.size() > 0) {
            for(HddcGeochemicalabnpointEntity hddcGeochemicalabnpoint : hddcGeochemicalabnpointList) {
                hddcGeochemicalabnpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeochemicalabnpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeochemicalabnpoint.setIsValid(PlatformConstants.N);
                this.hddcGeochemicalabnpointRepository.save(hddcGeochemicalabnpoint);
            }
        }
    }

}
